import { channelsType } from '@/store/reducer/channels';
import { AuthType } from '@/store/reducer/user';

export const TOKEN_KEY = 'geek-park-moblie';
// 取token
export const gettoken = (): AuthType => {
  return JSON.parse(localStorage.getItem(TOKEN_KEY) || '{}');
};
// 存token
export const settoken = (auth: AuthType): void => {
  localStorage.setItem(TOKEN_KEY, JSON.stringify(auth));
};
// 删token
export const cleartoken = (): void => {
  localStorage.removeItem(TOKEN_KEY);
};
// 有无token
export const hastoken = (): boolean => {
  return !!gettoken().token;
};

// 1. 封装操作频道数据的方法
const CHANNEL_KEY = 'itcast-geek-park-channel';

/**
 * 保存频道数据到本地
 * @param {*} channels
 */
export const setLocalChannels = (channels: channelsType[]) => {
  localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels));
};

/**
 * 获取本地的频道数据，如果没有数据，使用时注意空数组的判断
 * @returns
 */
export const getLocalChannels = (): channelsType[] => {
  return JSON.parse(localStorage.getItem(CHANNEL_KEY) || '[]');
};

/**
 * 删除本地的频道数据
 */
export const removeLocalChannels = () => {
  localStorage.removeItem(CHANNEL_KEY);
};

// 1. 封装方法

// 搜索关键字的本地缓存键名
const SEARCH_HIS_KEY = 'itcast_history';

/**
 * 从缓存获取搜索历史关键字
 */
export const getLocalHistories = (): string[] => {
  return JSON.parse(localStorage.getItem(SEARCH_HIS_KEY) || '[]');
};

/**
 * 将搜索历史关键字存入本地缓存
 * @param {Array} histories
 */
export const setLocalHistories = (histories: string[]) => {
  localStorage.setItem(SEARCH_HIS_KEY, JSON.stringify(histories));
};

/**
 * 删除本地缓存中的搜索历史关键字
 */
export const removeLocalHistories = () => {
  localStorage.removeItem(SEARCH_HIS_KEY);
};
